package com.groupten.MyController;

import com.groupten.Entity.QuestionEntity;
import com.groupten.Service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

@Slf4j
@RestController
@RequestMapping("group10/jyfcontroller")
public class jyfQuestionImportController {

    @Autowired
    private QuestionService questionService;

    @PostMapping("question/import")
    public ResponseEntity<String> importQuestionsFromCsv(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return ResponseEntity.badRequest().body("File is empty");
        }

        int successfulImports = 0; // 添加计数器
        QuestionEntity currentQuestion = null; // 当前正在处理的问题
        try (BufferedInputStream bis = new BufferedInputStream(multipartFile.getInputStream());
             BufferedReader br = new BufferedReader(new InputStreamReader(bis))) {
            String line;
            br.readLine(); // 跳过标题行
            while ((line = br.readLine()) != null) {
                String[] data = line.split(",");

                if (data.length > 7 && !data[0].isEmpty()) { // 检查是否为新的问题标识符
                    if (currentQuestion != null) {
                        if (questionService.removeDuplicateQuestion(currentQuestion)) {
                        // 如果当前问题不为空，则保存当前问题
                        questionService.insertQuestion(currentQuestion);
                        successfulImports++;
                    }}
                    currentQuestion = new QuestionEntity();
                    long questionId = parseLongWithCheck(data[0]);
                    int questionType = parseIntWithCheck(data[1]);
                    int questionSubject = parseIntWithCheck(data[2]);
                    int knowledgePoint = parseIntWithCheck(data[3]);
                    double score = parseDoubleWithCheck(data[4]);
                    double level = parseDoubleWithCheck(data[5]);
                    String questionText = data[6];
                    String answerText = data[7];
                    // 设置其他属性
                    currentQuestion.setQuestionId(questionId);
                    currentQuestion.setQuestionType(questionType);
                    currentQuestion.setSubject(questionSubject);
                    currentQuestion.setKnowledgePoint(knowledgePoint);
                    currentQuestion.setScore(score);
                    currentQuestion.setLevel(level);
                    currentQuestion.setQuestionText(questionText);
                    currentQuestion.setAnswerText(answerText);
                } else if (currentQuestion != null && data.length > 6) {
                    // 累积问题文本和答案文本
                    currentQuestion.setQuestionText(currentQuestion.getQuestionText() + "\n" + data[6]);
                    if (data.length > 7) {
                        currentQuestion.setAnswerText(currentQuestion.getAnswerText() + "\n" + data[7]);
                    }
                }
            }
            if (currentQuestion != null) {
                // 保存最后一个问题
                questionService.insertQuestion(currentQuestion);
                successfulImports++;
            }
            if (successfulImports == 0) {
                return ResponseEntity.ok("No valid questions were imported.");
            }
            return ResponseEntity.ok("CSV file has been imported successfully. Imported " + successfulImports + " questions.");
        } catch (Exception e) {
            log.error("Failed to import CSV file", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to import CSV file");
        }
    }

    private long parseLongWithCheck(String value) {
        try {
            return Long.parseLong(value.trim());
        } catch (NumberFormatException e) {
            log.error("Invalid long value: {}", value, e);
            return 0;
        }
    }

    private int parseIntWithCheck(String value) {
        try {
            return Integer.parseInt(value.trim());
        } catch (NumberFormatException e) {
            log.error("Invalid integer value: {}", value, e);
            return 0;
        }
    }

    private double parseDoubleWithCheck(String value) {
        try {
            return Double.parseDouble(value.trim());
        } catch (NumberFormatException e) {
            log.error("Invalid double value: {}", value, e);
            return 0.0;
        }
    }
}